package com.netty.client;

import com.nettryhomework.JsonDecoder;
import com.nettryhomework.JsonEncoder;
import com.nettryhomework.RpcRequest;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class RpcConsumer {

    private static ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    private UserClientHandler clientHandler;


    public Object createProxy(Class<?> serverClass){
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[]{serverClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            if( null == clientHandler){
                initClient();
            }
            RpcRequest rpcRequest = new RpcRequest(method.getDeclaringClass().getName(),method.getName(),method.getParameterTypes() ,args);
            clientHandler.setParam(rpcRequest);
                return executor.submit(clientHandler).get();
            }

        });
    }

    private void initClient() throws InterruptedException {
        clientHandler = new UserClientHandler();
        NioEventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY,true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline()
                                .addLast(new JsonEncoder())
                                .addLast(new StringDecoder())
                                .addLast(clientHandler);
                    }
                });
        bootstrap.connect("localhost",8990).sync();
    }

}
